
//1.  在纯函数组件 + redux 混合在一起

//2.  在纯函数组件 + mobx  

// context 隔空传递
// Provider 使用了context 传送store 
// Hooks 接合 redux (store dispatch action reducer)
// Hooks 接合 mobx  (action state  项目使用)
// 单向数据流  action - state - view  (action - reducer - dispatch  - store  )

// useReducer useContext 
import {useReducer,useContext,useRef,useEffect} from "react"
import { reducers } from "./store/reducers";
import { initState } from "./store/state";
import { GolBalContext } from "./store";
import {ajax} from "@/utils/request"

export function HooksRedux(){
  return (
    <div>
      <h2> Hooks + Redux +  react-redux </h2>
      <p>实现数据的集中式管理  (store state action reducers views)  </p>
      <AppMain></AppMain>
    </div>
  )
}


function AppMain(){
  return (
    <div>
      <hr/>
      <h2> Redux + Hooks 主视图 </h2>
      <AppBox></AppBox>
    </div>
  )
}

function AppBox(){
   const [ state,dispatch] = useReducer(reducers,initState)  // 传递 state 和 dispatch 基于context 
   return (
     <div>
       <h2> AppBox - AppBox - 根组件 </h2>
       <GolBalContext.Provider value={{state,dispatch}}>
          <Layout></Layout>
       </GolBalContext.Provider>
     </div>
   )
}

function Layout(){
  return (
    <div>
        <h2> Layout - Layout - 项目主页 </h2>
        <hr/>
        <ChildOne></ChildOne>
        <hr/>
        <ChildTwo></ChildTwo>
    </div>
  )
}

function ChildOne(){
  const {state,dispatch}  = useContext(GolBalContext) // 获取state 和dispatch context 
  console.log(state)
  const {count,word,city,flag} = state;
   return (
     <div>
       <h2> ChildOne - ChildOne - 1</h2>
      {
        flag&&<div>
           <h2>count -- {count }</h2>
        <h2>city === {city}</h2>
        <h2>word -- {word}</h2>
        </div>
      }
     </div>
   )
}

function ChildTwo(){
  const {state,dispatch}  = useContext(GolBalContext)
  const text = useRef();
  return (
    <div>
      <h2> ChildTwo - ChildTwo - 2</h2>
      <button onClick={()=>dispatch({type:"COUNTADD",payload:10})} >点击count add </button>
      <button onClick={()=>dispatch({type:"changeCIty",payload:'美丽的上海-杭州'})} >点击修改 city </button>
      <p> 
        <input type="text" value={state.word} ref={text} onChange={()=>dispatch({type:"changeWord",payload:text.current.value})} />
      </p>
      <button onClick={()=>dispatch({type:"changeflag",payload:!state.flag})} >changeflag </button>
   
      <hr/>
      <MyMovie></MyMovie>
    </div>
  )
}

const MyMovie = ()=>{
  const {state,dispatch} = useContext(GolBalContext)
  useEffect(()=>{
    getMoveiList()
  },[])

  const getMoveiList = async ()=>{
    let res = await ajax.get("http://localhost:4400/movie")
    dispatch({
      type:"GETMOVIE",
      payload:res.data.result 
    })
  }
  return (
    <div>
      <h2> Movie - 电影列表 </h2>
      {
        state.movie && state.movie.map((l,i)=>(
          <p key={i}>{l.title} --- {i} </p>
        ))
      }
    </div>
  )
}